<template>
  <div>
    {{ msg }}
    <input v-model="newMessage" placeholder="Type a message..." />
    <button @click="sendMessage">Send</button>
    <button @click="closeConnection">Disconnect</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      msg: "",
      newMessage: "",
      websocket: null, // 保存WebSocket对象
    };
  },
  created() {
    this.ws();
  },
  methods: {
    ws() {
      const name = "abc";
      let ws = new WebSocket(`ws://localhost:9090/api/chat?${name}`);
      ws.onopen = () => {
        console.log("已建立连接");
      };
      ws.onmessage = (event) => {
        console.log("正在接收消息");
        this.msg = event.data;
        console.log(event.data);
      };
      ws.onclose = () => {
        console.log("已断开连接");
      };
      // 将WebSocket对象保存在组件的data中，以便在发送消息时使用
      this.websocket = ws;
    },
    sendMessage() {
      if (this.newMessage) {
        console.log("正在发送消息");
        // 使用WebSocket的send方法发送消息
        let data = { sendid: 1, receivedid: 1, message: "你好" };
        let json = JSON.stringify(data);
        // this.websocket.send(this.newMessage);
        this.websocket.send(json);
        this.newMessage = "";
      }
    },
    closeConnection() {
      console.log("正在关闭连接");
      // 使用WebSocket的close方法关闭连接
      this.websocket.close();
    },
  },
};
</script>

<style>
</style>
